package com.tskj.mh.badminton.config;

import com.tskj.mh.badminton.quene.BadmintonThread;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @author LeonSu
 */
@Component
public class MainListener implements ApplicationListener<ApplicationEvent> {

    private BadmintonThread badmintonThread = null;

    private ApplicationContext webApplicationContext;

    @Value("${easystar.host}")
    private String host;

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ContextRefreshedEvent) {
            webApplicationContext = ((ContextRefreshedEvent)applicationEvent).getApplicationContext();
            if (webApplicationContext != null && badmintonThread == null) {
                badmintonThread = new BadmintonThread(webApplicationContext, host);

                ThreadPoolTaskExecutor asyncServiceExecutor = webApplicationContext.getBean(ThreadPoolTaskExecutor.class);
                asyncServiceExecutor.submit(badmintonThread);
            }
        }
        if (applicationEvent instanceof ContextStoppedEvent) {
            if (badmintonThread != null) {
                badmintonThread.close();
            }
        }
        if (applicationEvent instanceof ContextClosedEvent) {
            if (badmintonThread != null) {
                badmintonThread.close();
            }
        }
    }


}
